package singleton;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author liouwb
 * 单例模式 枚举
 */
public class SingletonEnumTest {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 单例 枚举
        SingletonEnum singletonEnum = SingletonEnum.getInstance();
        SingletonEnum singletonEnum1 = SingletonEnum.getInstance();

        // 通过反射实例
        Class<SingletonEnum> singletonEnumClass = SingletonEnum.class;
        Constructor<SingletonEnum> constructor = singletonEnumClass.getDeclaredConstructor();

        constructor.setAccessible(true);
        SingletonEnum singletonEnum2 = constructor.newInstance();

        // 验证单例是否全局只有一个实例
        System.out.println("正常获取的实例比较：" + (singletonEnum == singletonEnum1));
        // 反射获取与正常获取对比
        System.out.println("正常获取的实例比较：" + (singletonEnum == singletonEnum2));

        // 输出相应对象
        System.out.println("singletonEnum ：" + singletonEnum.hashCode());
        System.out.println("singletonEnum1：" + singletonEnum1.hashCode());
        System.out.println("singletonEnum2：" + singletonEnum2.hashCode());
    }


    /**
     * 枚举 单例
     */
    enum SingletonEnum {
        INSTANCE;

        public static SingletonEnum getInstance() {
            return INSTANCE;
        }
    }

}
